let app = getApp()
let socketOpen = false
let socketMsgQueue = []
import datetime from '../../utils/util.js';
Component({
    properties: {
 
      },
      data:{
        is_open:0,
        promptList: [],
        showPrompt:false,
        starNum: 0,
        checkedResult: 1,
        style_type: "star",
        keyboard: "0px",
        navArr: [ {
          url: "/static/image/chat-lxr.png",
          txt: "保存联系人"
      }, {
          url: "/static/image/chat-wx.png",
          txt: "加微信"
      }, {
          url: "/static/image/chat-dh.png",
          txt: "打电话"
      }, {
        url: "/static/image/chat-sc.png",
        txt: "预约"
      } ],
      },
      pageLifetimes: {
        show: function () {
           //this.wssInit()
        }
      },
    lifetimes: {
        attached: function () {
          var that=this  
          wx.onKeyboardHeightChange ((res) => {
            if(that.keyboard != res.height + "px"){
              console.log(res.height);
              that.setData({
                keyboard:res.height + "px"
              })
            }
          });
          this.sendSocket();
          //this.wssInit()
          wx.request({
            url: app.globalData.siteroot,
            data: {
              do:'Member_getUserCenter',
              user_id:wx.getStorageSync('user_id')
            },
            success: function(res) {
              wx.setStorageSync('staff_bind_id',res.data.data.member_data.staff_bind_id)
            }
          })
          that.setData({
            globalColor:app.globalData.globalColor,
            user_avatar:wx.getStorageSync('userinfo').user_headimg
          })
          Promise.all([
            that.getCode(wx.getStorageSync('userinfo').user_headimg)
           ]).then(res=>{
            that.setData({ 
              user_avatar:res[0].tempFilePath
            })
           })
           wx.request({
            url: app.globalData.siteroot,
            data: {
              do:'user_busStaff',
              user_id:wx.getStorageSync('user_id'),
              staff_id:wx.getStorageSync('staff_bind_id')
            },
            success: function(res) {
                var staff_id=res.data.info.staff_id
                var staff_chatid=res.data.info.staff_chatid
                that.setData({
                  staff_id:staff_id,
                  staff_chatid:staff_chatid
                })
                wx.request({
                  url: app.globalData.siteroot,
                  data: {
                    do:'Staff_getStaffInfo',
                    user_id:wx.getStorageSync('user_id'),
                    staff_id:staff_id
                  },
                  success: function(res) {
                      that.setData({
                        info:res.data.info,
                        staff_avatar:res.data.info.avatar
                      })
                  }
                })
                wx.request({
                  url: app.globalData.siteroot,
                  data: {
                    do:'Chat_getStaffInfo',
                    user_id:wx.getStorageSync('user_id'),
                    staff_chatid:staff_chatid,
                    user_openid:wx.getStorageSync('userinfo').openid,
                    page:1,
                    target: 2,
                    send_type: 1,
                    status: 2,
                  },
                  success: function(res) {
                      console.log(res.data)
                  }
                })
                wx.request({
                  url: app.globalData.siteroot,
                  data: {
                    do:'Chat_getMessage',
                    user_id:wx.getStorageSync('user_id'),
                    staff_chatid:staff_chatid,
                    user_openid:wx.getStorageSync('userinfo').openid,
                    page:1,
                    target: 2,
                    send_type: 1,
                    status: 2,
                  },
                  success: function(res) {
                    that.setData({
                      chatArr:res.data.data
                    })
                    wx.request({
                      url: app.globalData.siteroot,
                      data: {
                        do:'Chat_getQuestion',
                        user_id:wx.getStorageSync('user_id'),
                        staff_chatid:staff_chatid,
                        user_openid:wx.getStorageSync('userinfo').openid,
                        page:1,
                        target: 2,
                        send_type: 1,
                        status: 2,
                      },
                      success: function(res) {
                           var service={
                            create_time:res.data.info.curr_time,
                            target: 1,
                            title:res.data.info.tip_msg || "请问有什么可以帮到您的吗？您可以在这里跟我实时沟通。",
                            send_type: -1,
                            list:res.data.data
                          }
                          that.setData({
                            service:service,
                            oldlength:that.data.chatArr.length
                          })
                          var newchat= that.data.chatArr
                          newchat.push(service);
                          if(res.data.info.is_open=='0'){
                            that.setData({
                              is_open:false
                            })
                          }else{
                            that.setData({
                              is_open:true
                            })
                          }
                          that.setData({
                            style_type:res.data.info.icon_type,
                            promptList:res.data.common_lang,
                            chatArr:newchat,
                            scrollTop:100000
                          })
                      }
                    })
                  }
                })
              
            }
          })
        
       setInterval(() => {
            var msg = JSON.stringify({
              'data': 'ping'
          })
          wx.sendSocketMessage({
            data: msg,
            success: function (res) {
              console.log(res)
              console.log('发送心跳')
            },
            fail: function (res) { 
              console.log(res)
              console.log('心跳发送失败')}
           })
        }, 3000)
          
       }
      },
    methods: {
      sendSocket(){
        var that=this
        let ws=wx.connectSocket({
          url: app.globalData.vwss,
        })
        //打开socket连接,
        ws.onOpen(function(){
          // 发送消息给服务器端
          ws.send({
            data: JSON.stringify({
              type:"bind",
              uid:wx.getStorageSync('userinfo').openid,
              toid:'',
              image:0,
              msg:''
            }),
            success: res => {
              console.log(res+'发送成功')
            },
            fail: err=> {
              console.log(err+'失败')
            }
          })

      
        })
        //接收服务器端发来的数据
        ws.onMessage(function(res){
          console.log('接收返回')
          console.log(res)
          var res_data = JSON.parse(res.data);
          switch (console.log(res_data), res_data.type) {
            case "init":
              console.log('bind')
              break;

            case "ping":
              console.log('ping')
              break;

            case "notice":
              console.log('notice')
              break;
            case "close":
                console.log('重新链接')
                break;
            default:
              console.log('文字')
          }
          console.log(res_data.type)
          if(res_data.type=='say'||res_data.type=='image'){
            console.log(res_data.type+'00000')
            var nowtime= new Date().getTime();
            var s=datetime.formatDate(nowtime)
            var send_type=1
            if(res_data.type=='image'){
                send_type=2
            }
            var msg={
              staff_chatid:that.data.staff_chatid,
              user_openid:wx.getStorageSync('userinfo').openid,
              content:res_data.msg,
              create_time:s,
              target:1,
              send_type:send_type,
              status:0
            }
            that.data.chatArr.push(msg)
            for(var i=0;i<that.data.chatArr.length;i++){
              that.data.chatArr[i]['status']=1;
            }
            that.setData({
              scrollTop:that.data.scrollTop+100,
              isUser: true,
              chatArr: that.data.chatArr
            })
          }
        })
      },
      chooseval:function(e){
        this.setData({
          showPrompt:false,
          val:e.currentTarget.dataset.val
        })
      },
      changyong:function(){
          if(this.data.showPrompt){
            this.setData({
              showPrompt:false
            })
          }else{
            this.setData({
              showPrompt:true
            })
          }
      },
      pingjiasubmit:function(){
        var that=this
        wx.request({
          url: app.globalData.siteroot,
          data: {
            do:'Chat_chatEvaluate',
            staff_id:wx.getStorageSync('staff_bind_id'),
            user_id:wx.getStorageSync('user_id'),
            star_num:parseInt(that.data.starNum)+1,
            is_resolve:that.data.checkedResult
          },
          success: function(res) {
            wx.showToast({
              title: '评价成功！',
              icon: 'success',
              duration: 1500
            })
            that.setData({
              evaluateMask:false,
              evaluateVisible:false
            })
          }
        })
      },
      checkedResult:function(e){
        this.setData({
          checkedResult:e.currentTarget.dataset.id
        })
      },
      starchange:function(e){
        this.setData({
          starNum:e.currentTarget.dataset.num
        })
      },
      cancelpingjia:function(){
        this.setData({
          evaluateMask:false,
          evaluateVisible:false
        })
      },
      pingjia:function(){
        this.setData({
          evaluateMask:true,
          evaluateVisible:true
        })
      },
      upload_file: function (filePath) {
        var that = this;
        wx.uploadFile({
        url:app.globalData.siteroot+'&do=Index_uploadFile',
        filePath: filePath,
        name: 'file_upload',
        header: {
        'content-type': 'multipart/form-data'
        }, 
        formData: {
        'do':'Index_uploadFile',
        },
        success: function (res) {
          var data=JSON.parse(res.data)
          if(data.code==200){
            var c = that.formatDateTime();
            that.setData({
              val:data.info.url
            })
            that.sendimg();
          }
        },
        fail: function (res) {}
        })
      },
      uploadopen:function(){
        if(this.data.showMoreVisible){
          this.setData({
            showMoreVisible:false
          })
        }else{
          this.setData({
            showMoreVisible:true
          })
        }
      
      },
      uploadchoose:function(){
        var that = this;
        wx.chooseImage({
          success: function(t) {
            var a = t.tempFilePaths;
            that.upload_file(t.tempFilePaths[0])
          }
        })
      },
      questiondetail:function(e){
        wx.navigateTo({ 
          url: '/yb_shopv2/native/all/index?type=question_detail&id='+ e.currentTarget.dataset.id,
       })
      },
      
      
     
      sendmessage:function(){
        var that=this
        var send_time = this.formatDateTime();
        var t = JSON.stringify({
          type:"say",
          uid:wx.getStorageSync('userinfo').openid,
          toid:that.data.staff_chatid,
          image:0,
          msg:that.data.val
        })
        wx.sendSocketMessage({
          data: t,
          success: function(e) {
              console.log(e);
              console.log("发送成功");
          },
          fail: function(e) {
              console.log(e);
              console.log("发送失败000");
          }
       });
        wx.request({
          url: app.globalData.siteroot,
          data: {
            do:'Chat_putMessage',
            staff_id:wx.getStorageSync('staff_bind_id'),
            staff_chatid:that.data.staff_chatid,
            user_openid:wx.getStorageSync('userinfo').openid,
            page:2,
            send_type:1,
            status:2,
            target:2,
            content:that.data.val
          },
          success: function(res) {
            wx.request({
              url: app.globalData.siteroot,
              data: {
                do:'Buschat_msgList',
                staff_id:wx.getStorageSync('staff_bind_id'),
                chatid:that.data.staff_chatid,
              },
              success: function(res) {
              }
            })

            var service={
               create_time:send_time,
               content:that.data.val,
               target: 2,
               status: 2,
               send_type: 1
            }
            var newchat= that.data.chatArr
            newchat.push(service);
            that.setData({
              chatArr:newchat,
              scrollTop:that.data.scrollTop+100
            })
            that.setData({
              val:''
            })
          }
        })
      },
      sendimg:function(){
        var that=this
        var send_time = this.formatDateTime();
        var t = JSON.stringify({
          type:"say",
          uid:wx.getStorageSync('userinfo').openid,
          toid:that.data.staff_chatid,
          image:1,
          msg:that.data.val
        })
        wx.sendSocketMessage({
          data: t,
          success: function(e) {
              console.log(e);
              console.log("发送成功");
          },
          fail: function(e) {
              console.log(e);
              console.log("发送失败");
          }
        });
        wx.request({
          url: app.globalData.siteroot,
          data: {
            do:'Chat_putMessage',
            staff_id:wx.getStorageSync('staff_bind_id'),
            staff_chatid:that.data.staff_chatid,
            user_openid:wx.getStorageSync('userinfo').openid,
            page:2,
            send_type:2,
            status:2,
            target:2,
            content:that.data.val
          },
          success: function(res) {
            wx.request({
              url: app.globalData.siteroot,
              data: {
                do:'Buschat_msgList',
                staff_id:wx.getStorageSync('staff_bind_id'),
                chatid:that.data.staff_chatid,
              },
              success: function(res) {
              }
            })

            var service={
               create_time:send_time,
               content:that.data.val,
               target: 2,
               status: 2,
               send_type: 2
            }
            var newchat= that.data.chatArr
            newchat.push(service);
            that.setData({
              chatArr:newchat,
              scrollTop:that.data.scrollTop+100
            })
            that.setData({
              val:''
            })
          }
        })
      },
      formatDateTime: function() {
        var t = new Date(), e = t.getFullYear(), a = t.getMonth() + 1;
        a = a < 10 ? "0" + a : a;
        var o = t.getDate();
        o = o < 10 ? "0" + o : o;
        var s = t.getHours();
        s = s < 10 ? "0" + s : s;
        var n = t.getMinutes();
        n = n < 10 ? "0" + n : n;
        var i = t.getSeconds();
        return i = i < 10 ? "0" + i : i, e + "-" + a + "-" + o + " " + s + ":" + n + ":" + i;
    },
      talk:function(e){
        this.setData({
          val:e.detail.value
        })
      },
      getCode(img){
        return new Promise((resolve,reject)=>{
          wx.downloadFile({
            url: img,
            success: (res) => {
              resolve(res)
            }
          })
        })
      },
      conatct:function(e){
          const id = e.currentTarget.dataset.id;
          if(id==0)
          {
            var user_name=this.data.info.user_name;
            var phone=this.data.info.phone;
            if(user_name==''){
              return false
            }
            wx.addPhoneContact({
              firstName:user_name,
              mobilePhoneNumber:phone,
              success: function() {
                wx.showToast({
                  title:'保存成功',
                  icon:'success'
                })
              },
              fail: function() {
                console.log("取消保存");
              }
            })
          }
          else if(id==1){
            var wx_num=this.data.info.wx_num
            wx.showModal({
              title: '客服微信号',
              content:wx_num,
              showCancel: true,
              cancelText:"取消",
              confirmText:"点击复制",
              confirmColor: '#000000',
              success: function (res) {
                if (res.cancel) {
               } else{
                wx.setClipboardData({
                    data:wx_num,
                    success: function (res) {
                      wx.getClipboardData({
                        success: function (res) {
                          wx.showToast({
                            title: '复制成功'
                          })
                        }
                      })
                    }
                })
               }
               },
               fail: function (res) { },
               complete: function (res) { }
          })
          } else if(id == 2){
            let phone=this.data.info.phone
            wx.showModal({
              title: "是否要拨打这个电话？",
              content:phone,
              success: function(e) {
                  e.confirm ?   wx.makePhoneCall({
                    phoneNumber:phone,
                    success:function(){
                      wx.request({
                        url: app.globalData.siteroot,
                        data: {
                          do:'Video_updVideoTimes',
                          id:id,
                          staff_id:wx.getStorageSync('staff_bind_id'),
                          times_type:4,
                          user_id:wx.getStorageSync('user_id')
                        },
                        success: function(res) {
                        }
                      })
                    },
                    fail:function(){
                      console.log('拨打失败')
                    }
                  }) : e.cancel && console.log("用户点击取消");
              }
          })
          } else {
            var that = this;
            wx.showModal({
              title: "是否现在就要发起预约",
              content:"预约项目：" + that.data.info.services_name,
              success: function(e) {
                  e.confirm ?
                  wx.navigateTo({
                    url: '/yb_shopv2/native/all/index?type=good_detail&activity=service&goods_id=' + that.data.info.services_id,
                  }): 
                  e.cancel && console.log("用户点击取消");
              }
          })
          }
      }
    }
});
